package com.xiaoqi.store.controller;

import com.xiaoqi.store.entity.AddressEntity;
import com.xiaoqi.store.entity.JsonResult;
import com.xiaoqi.store.service.AddressService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

/**
 * @Author Rookie Coder
 * @Description
 * @Date
 **/
@RestController
@RequestMapping("/addresses")
@Slf4j
public class AddressController extends BaseController{

        @Autowired
        private AddressService addressService;

        /*
        * @Author xiaoqi
        * @Description  添加收货地址
        * @return
        **/
        @PostMapping("/addNewAddress")
        public JsonResult<Void> addNewAddress(AddressEntity addressEntity, HttpSession session){
            // 从session获取到uid的值
            Integer uidFromSession = getUidFromSession(session);
            // 从session中获取到uname的值
            String usernameFromSession = getUsernameFromSession(session);
            log.info("address的值"+ addressEntity.toString());
            // 调用业务层方法
            addressService.addUserAddress(addressEntity,uidFromSession,usernameFromSession);
            return new JsonResult<>(OK);
        }

        /*
        * @Author xiaoqi
        * @Description  查询所有的收货地址
        * @return
        **/
        @GetMapping({"", "/"})
        public JsonResult<List<AddressEntity>> selectUserAllAddress(HttpSession session){
            // 获取用户的uid
            Integer uidFromSession = getUidFromSession(session);
            List<AddressEntity> userAddressEntityList = addressService.selectUserAllAddress(uidFromSession);
            for (AddressEntity a: userAddressEntityList) {
                log.info("用户收货地址："+a);
            }
            return new JsonResult<>(OK, userAddressEntityList);
        }

        /*
        * @Author xiaoqi
        * @Description  修改默认地址
        * @return
        **/
        @PostMapping("{aid}/set_default")
        public JsonResult<Void> setUserDefaultAddress(@PathVariable("aid")Integer aid, HttpSession session){
           log.info("收货地址编号 "+aid);
            Integer uidFromSession = getUidFromSession(session);
            String usernameFromSession = getUsernameFromSession(session);
            addressService.updateUserDefaultAddress(aid,uidFromSession,usernameFromSession);
           return  new JsonResult<>(OK);
        }

        /*
        * @Author xiaoqi
        * @Description  删除收货地址
        * @return
        **/
        @PostMapping("{aid}/delete")
        public JsonResult<Void> deleteUserAddress(@Param("aid") Integer aid, HttpSession session){
            Integer uidFromSession = getUidFromSession(session);
            addressService.deleteAddressByAid(aid,uidFromSession);
            return new JsonResult<>(OK);
        }



}
